package com.tg.exception;

import com.auth0.jwt.exceptions.JWTDecodeException;
import com.tg.controller.Code;
import com.tg.controller.Result;
import com.tg.controller.ResultMessage;
import jakarta.validation.ConstraintViolationException;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;


@RestControllerAdvice
public class ProjectExceptionAdvice {
    @ExceptionHandler(Exception.class)
    public Result doException(Exception ex) {
        //记录日志
        //发送消息给运维
        //发送邮件给开发人员,ex对象发送给开发人员
        ex.printStackTrace();
        return new Result(Code.SYSTEM_UNKNOWN_ERR, null, ResultMessage.SYSTEM_UNKNOWN_ERR);
    }

    @ExceptionHandler(SystemException.class)
    public Result doSystemException(SystemException ex) {
        //记录日志
        //发送消息给运维
        //发送邮件给开发人员,ex对象发送给开发人员
        return new Result(ex.getCode(), null, ex.getMessage());
    }

    @ExceptionHandler(BusinessException.class)
    public Result doBusinessException(BusinessException ex) {
        ex.fillInStackTrace();
        return new Result(ex.getCode(), null, ex.getMessage());
    }

    @ExceptionHandler(BindException.class)
    public Result doAttributeTestException(BindException e){
        ResultMessage resultMessage = new ResultMessage();
        StringBuilder msg = new StringBuilder();
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
        for (ObjectError error : allErrors) {
            resultMessage.setMsg(msg.append(error.getDefaultMessage()));
        }
        System.out.println(resultMessage.getMsg().toString());
        return new Result(Code.ATTRIBUTE_ERR,null, resultMessage.getMsg().toString());
    }

    @ExceptionHandler(ConstraintViolationException.class)
    public Result doConstraintViolationException(ConstraintViolationException e){
        return new Result(Code.ATTRIBUTE_ERR,null, e.getMessage().substring(e.getMessage().indexOf(":")+1).trim());
    }

    @ExceptionHandler({PermissionException.class,JWTDecodeException.class})
    public Result doBusinessException(PermissionException ex) {
        return new Result(ex.getCode(), null, ex.getMessage());
    }
}
